package com.lagou.dao.impI;

import com.lagou.dao.AccountDao;
import com.lagou.domain.Account;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

/**
 * @Author wsl
 * @Date 2021/11/9 6:12
 * @Project_Name jdbc_spring
 */
public class AccountDaoImpI implements AccountDao {

    private QueryRunner queryRunner;

    //set方法的依赖注入
    public void setQueryRunner(QueryRunner queryRunner) {
        this.queryRunner = queryRunner;
    }

    //1.查询所有
    public List<Account> findAll() {

        List<Account> list = null;
        String sql = "select * from account";
        try {
            list = queryRunner.query(sql, new BeanListHandler<Account>(Account.class));
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }

    //2.根据id查询
    public Account findById(Integer id) {

        Account query = null;
        String sql = "select * from account where id = ?";
        try {
            query = queryRunner.query(sql, new BeanHandler<Account>(Account.class),id);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return query;
    }

    //3.新增操作
    public void save(Account account) {

        String sql = "insert into account values(null,?,?)";
        try {
            queryRunner.update(sql,account.getName(),account.getMoney());
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    //4.修改操作
    public void update(Account account) {

        String sql = "update account set name = ?,money = ? where id = ?";
        try {
            queryRunner.update(sql,account.getName(),account.getMoney(),account.getId());
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    //5.删除操作
    public void delete(Integer id) {

        String sql = "delete from account where id = ?";
        try {
            queryRunner.update(sql,id);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

}
